﻿using System;
using System.Collections.Generic;
using System.Data;

namespace JinYuan.VirtualDataLibrary
{
    public class DBSQL
    {

        /// <summary>
        /// 获取PLC换型参数绑定值
        /// </summary>
        /// <param name="modelName"></param>
        /// <returns></returns>
        public string GetPlcParamSql(string modelName)
        {
            string strSql = $@"SELECT 
                        '{modelName}' AS `ModelName`,
                        `pb`.`PLCAddress`,
                        `pc`.`PLCValue`,
                        `pc`.`UpdateTime`,
                        `pb`.`PLCRemark`,
                        `pb`.`OrderNum`
                   FROM 
                        `Plcconfigbase` `pb`
                   LEFT JOIN 
                        (SELECT * FROM `Plcconfig` WHERE `ModelName` = '{modelName}') `pc`
                   ON 
                        `pb`.`PLCAddress` = `pc`.`PLCAddress`
                   ORDER BY 
                        `pb`.`OrderNum`";

            return strSql;
        }

        /// <summary>
        /// 获取产品型号参数
        /// </summary>
        /// <param name="strModelType"></param>
        /// <returns></returns>
        public string GetParamSql(string strModelType)
        {
            string strSql = $@"SELECT 
                        `pb`.`ParaName`,
                        '{strModelType}' AS `ModelName`,
                        `pl`.`ParaValueMin`,
                        `pl`.`ParaValueMax`,
                        `pl`.`Uint`,
                        `pb`.`Remark`,
                        `pl`.`UpdateTime`
                   FROM 
                        `Parambase` `pb`
                   LEFT JOIN 
                        (SELECT * FROM `ParamList` WHERE `ModelName` = '{strModelType}') `pl`
                   ON 
                        `pb`.`ParaName` = `pl`.`ParaName`
                   ORDER BY 
                        `pb`.`fNo` ASC";

            return strSql;
        }


        /// <summary>
        /// 获取产品型号列表
        /// </summary>
        /// <param name="strProdType"></param>
        /// <returns></returns>
        public string GetProdTypeSql(string strProdType = "")
        {
            string strSql = @"SELECT * FROM ProductModel ";
            if (strProdType != "")
            {
                strSql += string.Format(" where  ModelName='{0}'", strProdType);
            }
            strSql += "  order by  ModelName";
            return strSql;
        }


        /// <summary>
        /// 获取产品型号
        /// </summary>
        /// <param name="strModelType"></param>
        /// <returns></returns>
        public string GetProductParaByProdModel(string strModelType)
        {
            string strSql = $@"SELECT 
                        `pb`.`ParaName`,
                        '{strModelType}' AS `ModelName`,
                        `pl`.`ParaValueMin`,
                        `pl`.`ParaValueMax`,
                        `pl`.`Uint`,
                        `pb`.`Remark`,
                        `pl`.`UpdateTime`
                   FROM 
                        `Parambase` `pb`
                   LEFT JOIN 
                        (SELECT * FROM `Paramlist` WHERE `ModelName` = '{strModelType}') `pl`
                   ON 
                        `pb`.`ParaName` = `pl`.`ParaName`
                   ORDER BY 
                        `pb`.`fNo` ASC";

            return strSql;
        }


        public string GetPLCConfigBases()
        {
            string strSql = string.Format(@"SELECT * FROM `Plcconfigbase` ORDER BY `OrderNum`");

            return strSql;
        }


        public string GetSysAdminSql()
        {
            string strSql = string.Format(@"SELECT 
                                    `LoginId`,
                                    `LoginName`,
                                    `LoginPwd`,
                                    `LoginUid`,
                                    `LoginLevel`,
                                    `SystemLog`,
                                    `CpkData`,
                                    `HistoryData`,
                                    `ParamSet`,
                                    `SystemSet`,
                                    `UserManage`
                               FROM 
                                    `SysAdmin`");

            return strSql;
        }

        /// <summary>
        /// 查询历史数据
        /// </summary>
        /// <param name="strBarCode"></param>
        /// <param name="strDate1"></param>
        /// <param name="strDate2"></param>
        /// <returns></returns>
        public string SelectHostData(int type, string strRfid, string strBarCode, string strDate1, string strDate2)
        {
            string strSql = "";
            if (type == 0)
            {
                strSql = @"SELECT 
                            `ChannelNo`,
                            DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `TestTime`,
                            `RFID`,
                            `BarCode`,
                            `Result`,
                            `Remark`,
                            CASE WHEN `Flag` = 1 THEN 'True' ELSE 'False' END AS `Flag`
                       FROM 
                            `AGearEntity`
                       WHERE 
                            `TestTime` >= '" + strDate1 + "' AND `TestTime` <= '" + strDate2 + "'";

                if (strRfid != "")
                {
                    strSql += " AND `RFID` LIKE '%" + strRfid + "'";
                }
                if (strBarCode != "")
                {
                    strSql += " AND `BarCode` LIKE '%" + strBarCode + "'";
                }
            }
            else if (type == 1)
            {
                #region 旧
                //string key = "FrmHistory_dgv_Main_";
                //strSql = @" SELECT 
                //                `ChannelNo` AS `通道`,
                //                DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `时间`,
                //                `RFID` AS `托杯码`,
                //                `BarCode` AS `钢壳码`,
                //                `WindSpeed` AS `离子风速流量`,
                //                `WindDeviceNum` AS `离子风清洁设备号`,
                //                `CCDFaceTestDeviceNum1` AS `端面检测设备号1`,
                //                `CCDFaceTestDeviceNum2` AS `端面检测设备号2`,
                //                `CCDFaceTestDeviceNum3` AS `端面检测设备号3`,
                //                `CCDFaceTestDeviceNum4` AS `端面检测设备号4`,
                //                `CCDCylinderTestDeviceNum1` AS `柱面检测设备号1`,
                //                `CCDCylinderTestDeviceNum2` AS `柱面检测设备号2`,
                //                `CCDCylinderTestDeviceNum3` AS `柱面检测设备号3`,
                //                `CCDPosFaceTestResult` AS `正极端面检测结果`,
                //                `CCDNegFaceTestResult` AS `负极端面检测结果`,
                //                `CCDBeforeCoatedCylinderTestResult` AS `包膜前圆柱面检测结果`,
                //                `CCDPosCylinderTestResult` AS `正极柱面检测结果`,
                //                `CCDNegCylinderTestResult` AS `负极柱面检测结果`,
                //                `Result` AS `综合结果`,
                //                `Info` AS `NG详情`,
                //                `Remark` AS `备注`,
                //                CASE WHEN `Flag` = 1 THEN '已上传' ELSE '未上传' END AS `上传状态`
                //            FROM `BGearEntity` where `TestTime` >= '" + strDate1 + "' and `TestTime` <= '" + strDate2 + "' ";
                #endregion

                strSql = @" SELECT 
                                `ChannelNo`,
                                DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS TestTime,
                                `RFID`,
                                `BarCode`,
                                `WindSpeed`,
                                `WindDeviceNum`,
                                `CCDFaceTestDeviceNum1`,
                                `CCDFaceTestDeviceNum2`,
                                `CCDFaceTestDeviceNum3`,
                                `CCDFaceTestDeviceNum4`,
                                `CCDCylinderTestDeviceNum1`,
                                `CCDCylinderTestDeviceNum2`,
                                `CCDCylinderTestDeviceNum3`,
                                `CCDNegativeTerminalWeldingZone2DInspectionResult`,
                                `CCDNegativeTerminalWeldingZone2DInspectionNGReasons`,
                                `CCDCoverPlate2DInspectionResult`,
                                `CCDCoverPlate2DInspectionNGReasons`,
                                `CCDNegativeTerminalWeldingZone25DInspectionResult`,
                                `CCDNegativeTerminalWeldingZone25DInspectionNGReasons`,
                                `CCDCoverPlate25DInspectionResult`,
                                `CCDCoverPlate25DInspectionNGReasons`,
                                `CCDTerminalPost2DInspectionResult`,
                                `CCDTerminalPost2DInspectionNGReasons`,
                                `CCDTerminalPost3DInspectionResult`,
                                `CCDTerminalPost3DInspectionNGReasons`,
                                `CCDSealingNail2DInspectionResult`,
                                `CCDSealingNail2DInspectionNGReasons`,
                                `CCDSealingNail3DInspectionResult`,
                                `CCDSealingNail3DInspectionNGReasons`,
                                `CCDTopFillet25DInspectionResult`,
                                `CCDTopFillet25DInspectionNGReasons`,
                                `CCDBottomFillet25DInspectionResult`,
                                `CCDBottomFillet25DInspectionNGReasons`,
                                `CCDCylindricalSurface25DInspectionResult`,
                                `CCDCylindricalSurface25DInspectionNGReasons`,
                                `CCDCylindricalSurface3DInspectionResult`,
                                `CCDCylindricalSurface3DInspectionNGReasons`,
                                `Result`,
                                `Info`,
                                `Remark`,
                            CASE WHEN `Flag` = 1 THEN 'True' ELSE 'False' END AS Flag
                            FROM `BGearEntity` WHERE `TestTime` >= '" + strDate1 + "' AND `TestTime` <= '" + strDate2 + "' ";
                if (strRfid != "")
                {
                    strSql += " AND `RFID` LIKE '%" + strRfid + "'";
                }
                if (strBarCode != "")
                {
                    strSql += " AND `BarCode` LIKE '%" + strBarCode + "'";
                }
            }
            else if (type == 2)//进站未上传
            {
                strSql = @"SELECT 
                            `ChannelNo`,
                            DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `TestTime`,
                            `RFID`,
                            `BarCode`,
                            `Result`,
                            `Remark`,
                            CASE WHEN `Flag` = 1 THEN 'True' ELSE 'False' END AS `Flag`
                       FROM 
                            `AGearEntity`
                       WHERE 
                            `TestTime` >= '" + strDate1 + "' AND `TestTime` <= '" + strDate2 + "'" +
                       "AND Flag = 2";

                if (strRfid != "")
                {
                    strSql += " AND `RFID` LIKE '%" + strRfid + "'";
                }
                if (strBarCode != "")
                {
                    strSql += " AND `BarCode` LIKE '%" + strBarCode + "'";
                }
            }
            else if (type == 3)//出站未上传
            {
                strSql = @" SELECT 
                                `ChannelNo`,
                                DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS TestTime,
                                `RFID`,
                                `BarCode`,
                                `WindSpeed`,
                                `WindDeviceNum`,
                                `CCDFaceTestDeviceNum1`,
                                `CCDFaceTestDeviceNum2`,
                                `CCDFaceTestDeviceNum3`,
                                `CCDFaceTestDeviceNum4`,
                                `CCDCylinderTestDeviceNum1`,
                                `CCDCylinderTestDeviceNum2`,
                                `CCDCylinderTestDeviceNum3`,
                                `CCDNegativeTerminalWeldingZone2DInspectionResult`,
                                `CCDNegativeTerminalWeldingZone2DInspectionNGReasons`,
                                `CCDCoverPlate2DInspectionResult`,
                                `CCDCoverPlate2DInspectionNGReasons`,
                                `CCDNegativeTerminalWeldingZone25DInspectionResult`,
                                `CCDNegativeTerminalWeldingZone25DInspectionNGReasons`,
                                `CCDCoverPlate25DInspectionResult`,
                                `CCDCoverPlate25DInspectionNGReasons`,
                                `CCDTerminalPost2DInspectionResult`,
                                `CCDTerminalPost2DInspectionNGReasons`,
                                `CCDTerminalPost3DInspectionResult`,
                                `CCDTerminalPost3DInspectionNGReasons`,
                                `CCDSealingNail2DInspectionResult`,
                                `CCDSealingNail2DInspectionNGReasons`,
                                `CCDSealingNail3DInspectionResult`,
                                `CCDSealingNail3DInspectionNGReasons`,
                                `CCDTopFillet25DInspectionResult`,
                                `CCDTopFillet25DInspectionNGReasons`,
                                `CCDBottomFillet25DInspectionResult`,
                                `CCDBottomFillet25DInspectionNGReasons`,
                                `CCDCylindricalSurface25DInspectionResult`,
                                `CCDCylindricalSurface25DInspectionNGReasons`,
                                `CCDCylindricalSurface3DInspectionResult`,
                                `CCDCylindricalSurface3DInspectionNGReasons`,
                                `Result`,
                                `Info`,
                                `Remark`,
                            CASE WHEN `Flag` = 1 THEN 'True' ELSE 'False' END AS Flag
                            FROM `BGearEntity` WHERE `TestTime` >= '" + strDate1 + "' AND `TestTime` <= '" + strDate2 + "'" +
                            "AND Flag = 2";
                if (strRfid != "")
                {
                    strSql += " AND `RFID` LIKE '%" + strRfid + "'";
                }
                if (strBarCode != "")
                {
                    strSql += " AND `BarCode` LIKE '%" + strBarCode + "'";
                }
            }
            #region 旧
            //else if (type == 2)
            //{
            //    strSql = @"SELECT 
            //                `ChannelNo` AS `通道`,
            //                DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:%i:%s') AS `时间`,
            //                `MaterialCode` AS `料盘码`,
            //                `MaterialCodes` AS `物料编码`,
            //                `EquipNum` AS `设备编号`,
            //                `Result` AS `结果`,
            //                `Remark` AS `备注`,
            //                CASE WHEN `Flag` = 1 THEN '已上传' ELSE '未上传' END AS `上传状态`
            //           FROM 
            //                `CGearEntity`
            //           WHERE 
            //                `TestTime` >= '" + strDate1 + "' AND `TestTime` <= '" + strDate2 + "'";

            //    if (strBarCode != "")
            //    {
            //        strSql += " AND `MaterialCode` LIKE '" + strBarCode + "%'";
            //    }
            //}
            #endregion

            return strSql;
        }


        /// <summary>
        /// 查询报警历史数据
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="alarmType"></param>
        /// <returns></returns>
        public string SelectHostAlarmData(string start, string end, int alarmType)
        {
            string strSql = "";
            switch (alarmType)
            {
                case 1:
                    strSql = @"SELECT 
                    DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
                    `PLCAdress`,
                    `AlarmContent`,
                    `AlarmCount`,
                    `Class`
               FROM 
                    `AlarmCountEntry`
               WHERE 
                    `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + $"' AND `Class` = '{CommonMethods.strClass}'";
                    break;
                case 2:
                    strSql = @"SELECT 
                    DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
                    `PLCAdress`,
                    `AlarmContent`,
                    `AlarmCount`,
                    `Class`
               FROM 
                    `AlarmCountEntry`
               WHERE 
                    `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + $"' AND `Class` = '{CommonMethods.strClass}'";
                    break;
                default:
                case 0:
                    strSql = @"SELECT 
                    DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
                    `PLCAdress`,
                    `AlarmContent`,
                    `AlarmCount`,
                    `Class`
               FROM 
                    `AlarmCountEntry`
               WHERE 
                    `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "'";
                    break;
            }
            #region 旧
            //if (alarmType == "全天")
            //{
            //    strSql = @"SELECT 
            //        DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
            //        `PLCAdress`,
            //        `AlarmContent`,
            //        `AlarmCount`,
            //        `Class`
            //   FROM 
            //        `AlarmCountEntry`
            //   WHERE 
            //        `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "'";
            //}
            //else if (alarmType == "白班")
            //{
            //    strSql = @"SELECT 
            //        DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
            //        `PLCAdress`,
            //        `AlarmContent`,
            //        `AlarmCount`,
            //        `Class`
            //   FROM 
            //        `AlarmCountEntry`
            //   WHERE 
            //        `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "' AND `Class` = '白班'";
            //}
            //else
            //{
            //    strSql = @"SELECT 
            //        DATE_FORMAT(`AlarmTime`, '%Y-%m-%d %H:%i:%s') AS `AlarmTime`,
            //        `PLCAdress`,
            //        `AlarmContent`,
            //        `AlarmCount`,
            //        `Class`
            //   FROM 
            //        `AlarmCountEntry`
            //   WHERE 
            //        `AlarmTime` >= '" + start + "' AND `AlarmTime` <= '" + end + "' AND `Class` = '夜班'";
            //}
            #endregion
            return strSql;
        }

        /// <summary>
        /// 按日统计
        /// </summary>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public string GetStaticByDay(string startDateTime, string endDateTime)
        {
            string strSql = $@"SELECT 
                        DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:00:00') AS `Day`,
                        `ProdIn`,
                        `ProdOut`,
                        `Ppm`,
                        CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN `ProdIn` > 0 THEN ROUND(COALESCE(`ProdOut`, 0) / COALESCE(`ProdIn`, 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'
                   GROUP BY 
                        `TestTime`, `ProdOut`, `ProdIn`, `Ppm`, `JiaDL`
                   UNION ALL
                   SELECT 
                        'Total' AS `Day`,
                        SUM(`ProdIn`) AS ProdIn,
                        SUM(`ProdOut`) AS ProdOut,
                        AVG(`Ppm`) AS Ppm,
                        CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'";

            return strSql;
        }

        /// <summary>
        /// 按周查询
        /// </summary>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public string GetStaticByWeek(string startDateTime, string endDateTime)
        {
            string strSql = $@"SELECT 
                        DATE_FORMAT(`TestTime`, '%Y-%m') AS `Week`,
                        SUM(`ProdIn`) AS ProdIn,
                        SUM(`ProdOut`) AS ProdOut,
                        AVG(`Ppm`) AS Ppm,
                        CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'
                   GROUP BY 
                        DATE_FORMAT(`TestTime`, '%Y-%m'), `JiaDL`
                   UNION ALL
                   SELECT 
                        'Total' AS `Week`,
                        SUM(`ProdIn`) AS ProdIn,
                        SUM(`ProdOut`) AS ProdOut,
                        AVG(`Ppm`) AS Ppm,
                        CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'";

            return strSql;
        }


        /// <summary>
        /// 按月查询
        /// </summary>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public string GetStaticByMonth(string startDateTime, string endDateTime)
        {
            string strSql = $@"SELECT 
                        DATE_FORMAT(`TestTime`, '%Y-%m') AS `Month`,
                        SUM(`ProdIn`) AS ProdIn,
                        SUM(`ProdOut`) AS ProdOut,
                        AVG(`Ppm`) AS Ppm,
                        CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'
                   GROUP BY 
                        DATE_FORMAT(`TestTime`, '%Y-%m'), `JiaDL`
                   UNION ALL
                   SELECT 
                        'Total' AS `Month`,
                        SUM(`ProdIn`) AS ProdIn,
                        SUM(`ProdOut`) AS ProdOut,
                        AVG(`Ppm`) AS Ppm,
                        CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{startDateTime}' AND '{endDateTime}'";

            return strSql;
        }

        /// <summary>
        /// 按班次统计
        /// </summary>
        /// <param name="dateTime"></param>
        /// <param name="shift"></param>
        /// <param name="changeShiftTime"></param>
        /// <returns></returns>
        public string GetStaticByShift(DateTime dateTime, int shift, string changeShiftTime)
        {
            string sDateTime1 = string.Empty;
            string sDateTime2 = string.Empty;
            if (shift == 0)// 白班
            {
                DateTime sTempDateTime = Convert.ToDateTime($"{dateTime.ToString("yyyy-MM-dd")} {changeShiftTime}");

                sDateTime1 = sTempDateTime.AddHours(-12).ToString("yyyy-MM-dd HH:mm:ss");
                sDateTime2 = sTempDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                sDateTime1 = $"{dateTime.ToString("yyyy-MM-dd")} {changeShiftTime}";
                sDateTime2 = Convert.ToDateTime(sDateTime1).AddHours(12).ToString("yyyy-MM-dd HH:mm:ss");
            }

            string strsql = $@"SELECT 
                        DATE_FORMAT(`TestTime`, '%Y-%m-%d %H:00:00') AS `TestTime`,
                        `ProdIn`,
                        `ProdOut`,
                        `Ppm`,
                        CONCAT(CAST(ROUND(`JiaDL` * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN `ProdIn` > 0 THEN ROUND(COALESCE(`ProdOut`, 0) / COALESCE(`ProdIn`, 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{sDateTime1}' AND '{sDateTime2}'
                   GROUP BY 
                        `TestTime`, `ProdOut`, `ProdIn`, `Ppm`, `JiaDL`
                   UNION ALL
                   SELECT 
                        'Total' AS `Time`,
                        SUM(`ProdIn`) AS ProdIn,
                        SUM(`ProdOut`) AS ProdOut,
                        AVG(`Ppm`) AS Ppm,
                        CONCAT(CAST(ROUND(AVG(`JiaDL`) * 100, 1) AS CHAR(10)), '%') AS `JiaDL`,
                        CONCAT(CAST(
                            CASE 
                                WHEN SUM(`ProdIn`) > 0 THEN ROUND(COALESCE(SUM(`ProdOut`), 0) / COALESCE(SUM(`ProdIn`), 0) * 100, 2)
                                ELSE 0 
                            END AS CHAR(10)), '%') AS `Prod`
                   FROM 
                        `Hourprod`
                   WHERE 
                        `TestTime` BETWEEN '{sDateTime1}' AND '{sDateTime2}'";

            return strsql;
        }
        /// <summary>
        /// 获取进站信息
        /// </summary>
        /// <returns></returns>
        public string GetInTime(string strBarCode)
        {
            string strSql = $@"SELECT TestTime 
                          ,BarCode 
                          ,Result 
                          ,Remark
                            FROM AGearEntity
                            WHERE BarCode = '{strBarCode}'
                            ORDER BY TestTime ASC";

            return strSql;
        }

        /// <summary>
        /// 获取最新的数据
        /// </summary>
        /// <returns></returns>
        public string GetStatic(string strDateTime)
        {

            string strsql = $@" SELECT [FDate]
                                      ,[FHour]
                                      ,[ProdIn]
                                      ,[ProdOut]                                     
                                      ,[TestTime]
                                  FROM [dbo].[Hourprod] where FDate='{strDateTime}' order by TestTime desc";
            return strsql;
        }

        /// <summary>
        /// 根据条码获取进站时间最新的一条数据
        /// </summary>
        /// <param name="strProdType"></param>
        /// <returns></returns>
        public string GetInStationTop1Sql(string barCode)
        {
            string strSql = $@"SELECT
                                    `ChannelNo`,
                                    `TestTime`,
                                    `RFID`,
                                    `BarCode`,
                                    `Result`,
                                    `Remark`,
                                    `Flag`
                                FROM 
                                    `AGearEntity`
                                WHERE `BarCode` = '{barCode}' ORDER BY `TestTime` DESC
                                LIMIT 1";
            return strSql;
        }

        /// <summary>
        /// 获取表头注释 按照设计顺序
        /// </summary>
        /// <returns></returns>
        public string GetSqlFields(string tableName)
        {
            string strSql = $@"SELECT
                                COLUMN_NAME,
                                DATA_TYPE,
                                COLUMN_COMMENT
                            FROM
                                INFORMATION_SCHEMA.COLUMNS
                            WHERE
                                TABLE_SCHEMA = 'largesquareone' AND TABLE_NAME = '{tableName}'
                            ORDER BY
                                ORDINAL_POSITION;";
            return strSql;
        }

        /// <summary>
        /// 根据标志位获取过程数据
        /// </summary>
        /// <param name="Flag"></param>
        /// <returns></returns>
        public string GetOutFlag1Sql(string Flag1)
        {
            string strSql = $@"SELECT
                                    *
                                FROM 
                                    `BGearEntity`
                                WHERE `Flag1` = '{Flag1}' ";
            return strSql;
        }

        /// <summary>
        /// 根据条码获取两台内相同条码数据
        /// </summary>
        /// <param name="barCode"></param>
        /// <returns></returns>
        public string GetOutCcdResultSql(string barCode)
        {
            string strSql = $@"SELECT
                                    `BarCode`
                                FROM 
                                    `BGearEntity`
                                WHERE `TestTime` > NOW() - INTERVAL 1 DAY
                                AND `BarCode` = '{barCode}' ";
            return strSql;
        }
    }

    public class M_DBCtrl
    {
        /// <summary>--本机数据库表名
        /// 
        /// </summary>
        //public string machineInSQLTable = "agearentity";
        public string machineOutSQLTable = "bgearentity";

        private string[] headerTextOut;
        /// <summary>
        /// 出站数据库表头
        /// </summary>
        public string[] HeaderTextOut
        {
            get { return headerTextOut; }
            set { headerTextOut = value; }
        }

        /// <summary>查询SQL数据库中的数据,并以string数组列表形式返回
        /// 
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns>所查询到的数据，null表示不存在</returns>
        public List<string[]> SQLAllDataSearchToStrArrList(string strSql)
        {
            List<string[]> strResArrList = new List<string[]>();
            List<string> strResList = new List<string>();
            try
            {
                using (DataTable dt = CommonMethods.db.QueryDataTable(strSql))
                {
                    if (dt != null)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            for (int j = 0; j < dt.Columns.Count; j++)
                            {
                                string resRow = dt.Rows[i][j].ToString();
                                strResList.Add(resRow);
                            }
                            string[] strResArr = strResList.ToArray();
                            strResList.Clear();
                            strResArrList.Add(strResArr);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return strResArrList = new List<string[]>();
            }
            return strResArrList;
        }

        /// <summary>根据下标在返回的数据库表信息 集合中获取相应数据
        /// index 0:字段 2:中文注释 1:变量类型int\char等
        /// </summary>
        /// <param name="SqlList">liststring[]类型的集合</param>
        /// <param name="index">string[] 的下标</param>
        /// <returns></returns>
        public String[] HeaderTextAssignment(List<string[]> SqlList, int index)
        {
            string[] headStringlist = new string[SqlList.Count];
            //  int i = 0;
            try
            {
                for (int i = 0; i < SqlList.Count; i++)
                {
                    headStringlist[i] = SqlList[i][index];
                }
            }
            catch (Exception)
            {
            }
            return headStringlist;
        }
    }
}
